package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.bean.Medicine;
import com.example.demo.bean.QueryInfo;
import com.example.demo.dao.MedicineDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
public class MedicineController {
    @Autowired
    MedicineDao medicineDao;

    //获取所有药品
    @RequestMapping("/getAllMedicine")
    public String getAllMedicine(QueryInfo queryInfo){
        //System.out.println(queryInfo.getQuery());
        //获取药品数量
        int  numbers =  medicineDao.getMedicineCounts("%"+queryInfo.getQuery()+"%");
        //开始页面
        int pageStart = (queryInfo.getPageStart()-1)*queryInfo.getPageSize();

        List<Medicine> medicines = medicineDao.getAllMedicine("%"+queryInfo.getQuery()+"%",pageStart,queryInfo.getPageSize());
        //System.out.println(medicines.get(0));
        HashMap <String, Object> res = new HashMap();
        //错误-404；成功-200
        int status = 200;
        res.put("code",status);
        res.put("total",numbers);
        res.put("data",medicines);
        String s = JSON.toJSONString(res);
        return s;
    }

    //添加药品
    @PostMapping("/addMedicine")
    public Integer addMedicine(@RequestBody Medicine medicine){
        //如果id不为0则表示修改
        if(medicine.getId()!=0)
            return medicineDao.editMedicine(medicine);
        else    //id为0则为添加
            return medicineDao.addMedicine(medicine);
    }

    //删除药品信息
    @DeleteMapping("/deleteMedicine/{id}")
    public Integer deleteMedicine(@PathVariable Integer id){
        System.out.println(id);
        return medicineDao.deleteMedicine(id);
    }
}
